<?php
declare (strict_types = 1);

namespace app\auth\controller;

use app\auth\BaseController;
use app\auth\common\util\ApiUtil;
use app\auth\service\DeptService;
use think\facade\Db;

class DeptController extends BaseController
{

    public function __construct(DeptService $deptService)
    {
        $this->deptService = $deptService;
    }

    public function list(){
        $params = request()->param();
        $where = $limit = array();
        $limit['page'] = !empty($params['page'])?intval($params['page']):1;
        $limit['pagesize'] = !empty($params['pagesize'])?intval($params['pagesize']):10;
        $name = $params['name']??null;
        if(!empty($name)) $where[] = ['name','like', '%'.$name.'%'];
        $total = $this->deptService->count($where);
        $list = $this->deptService->list($where , $limit);
        return ApiUtil::normal(['total'=>$total,'list'=>$list]);
    }

    // 创建部门
    public function add(){
        $params = request()->param();
        $name = $params['name']??null;
        if(empty($name)) return ApiUtil::normal(null, "请输入部门名称", ApiUtil::CODE_FAIL);
        if($this->deptService->count(['name'=>$name])) return ApiUtil::normal(null,'已存在部门',ApiUtil::CODE_FAIL);
        DB::startTrans();
        try{
            $data = array();
            $data['name'] = $name;
            $data['createtime'] = time();
            $lastId = $this->deptService->insertGetId($data);
            empty($lastId) && ApiUtil::abort('创建部门失败');
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return ApiUtil::excep($e);
        }
        return ApiUtil::normal(['id'=>$lastId]);
    }

    public function update(){
        $id = input('id',0);
        $name = input('name',null);
        if(empty($id)) return ApiUtil::normal(null, "部门ID不能为空", ApiUtil::CODE_FAIL);
        if(empty($name)) return ApiUtil::normal(null, "请输入部门名称", ApiUtil::CODE_FAIL);
        if($this->deptService->count([['id','<>',$id],['name','=',$name]])) return ApiUtil::normal(null, "部门名称已存在", ApiUtil::CODE_FAIL);
        $update = $this->deptService->update(['id'=>$id],['name'=>$name]);
        if(!$update) return ApiUtil::normal(null, "修改失败", ApiUtil::CODE_FAIL);
        return ApiUtil::normal(['id'=>$id]);
    }

    public function delete(){
        $ids = input('ids',[]);
        if (empty($ids)) return ApiUtil::normal(null, "请传入要删除的部门", ApiUtil::CODE_FAIL);
        $del = $this->deptService->delete(['id',$ids]);
        if(!$del) return ApiUtil::normal(null, "删除失败", ApiUtil::CODE_FAIL);
        return ApiUtil::normal(['id'=>$ids]);
    }
}
